//============================================================
// pour compiler sour LINUX: 
//               gcc -O2 -lpthread -o SLP  TCP_serv_LPT.c
//============================================================

// ! ! ! !   Version a modifier ici________>>>

                                            #define VERSION "(v4.2)"
                                            
/* ------    +--------------------+     -------------------------------
    LCD :    |18:23:32  1 2 12    |
             |C__N_T         #####|
             |3:230 345 345       |
             |T= 20.2 / 14.3 C    |
             +--------------------+
    Serveur TCP (connectable par telnet 8232 ou 8888 ou autre.....)
    qui permet :
     - de se connecter entre 2 machines
     - rebondir vers une troisieme si "reply" est utiliser 
     - ecouter le port RS232
     - parler sur le port paralelle LPT (pour affichage LCD)
     - affiche l heure
     - surveille ce qui passe sur les bus (RS ou LPT)    
     
     Ce programme utilise 5 thread avec indicateurs de bonne sante affiche ds le status
     (commande = "status" ou "s")                                     
     
     Noms des thread et fct appelees :                                        
          &thread1,  *socket_function 
          &thread2,  *RS232_read
          &thread3,  *connect_client 
          &thread4,  *read_for_client 
          &thread5,  *HEURE_auto 
          &thread6   *UNO_read_non_blocking( void *ptr )
          

Auteur: Christophe Chabbert
---------------------------------------------------------------------------*/

#include <stdio.h>
//Trav TCP
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>


#include <pthread.h> //cc Thread

#include <arpa/inet.h>
#include <sys/un.h>


#include <netdb.h> //cc client

#include <sys/io.h> //LPT
#include <time.h>
#include <sys/time.h>//micro sec



#include <termios.h> // RS232
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/signal.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>

#define BAUDRATE B1200
#define devicename  "/dev/ttyS0"
#define UNOname  "/UNO"
#define _POSIX_SOURCE 1         //POSIX compliant source
#define FALSE 0
#define TRUE 1  //RS232

#define MYPORT 9987 
#define BACKLOG 5  
#define MAXCLIENTS 5
#define MAXDATASIZE 21024


#define BASEPORT 0x378 /* lp1 */
#define CMD 0
#define DATA 1

// these evaluate to non-zero if the flag is set
#define b1(x)      (x & 0x01)  // 0000 0001
#define b2(x)      (x & 0x02)  // 0000 0010
#define b3(x)      (x & 0x04)  // 0000 0100  
#define b4(x)      (x & 0x08)  // 0000 1000
#define b5(x)      (x & 0x10)  // 0001 0000
#define b6(x)      (x & 0x20)  // 0010 0000
#define b7(x)     (x & 0x40)  // 0100 0000 
#define b8(x)     (x & 0x80)  // 1000 0000


#define lsb2(x)     (x & 15)  // 0000 1111
#define msb2(x)     ((x & 240) / 16) // 1111 0000 = 255 -15 = 240
#define lsb(x)     (x & 15)  // 0000 1111
#define msb(x)     ((x >> 4)) // decale de 4 bits a droite

void *socket_function( void *ptr );
void *connect_client( void *ptr );
void *read_for_client( void *ptr );
void *RS232_read( void *ptr );
void *HEURE_auto( void *ptr );
void *UNO_read_non_blocking( void *ptr );

void fct_send_line(int soc, char* data);
void signal_handler_IO (int status);    //definition of signal handler RS232 UNO
volatile int STOP=FALSE; //RS232 UNO

//====================================================================
void fct_hist(int soc){

      char line[2048];


sprintf (line, "\n_________________HISTO_____________________________\n");fct_send_line(soc,line);
sprintf (line, " v0.1  (21/03/11) : basic TCP server (select fct)\n");fct_send_line(soc,line);
sprintf (line, " v0.2  (21/03/11) : add Main thread to STOP server \n");fct_send_line(soc,line);
sprintf (line, " v0.3  (22/03/11) : add Thread to 2 multi-client (2x5)\n");fct_send_line(soc,line);
sprintf (line, " v1.0  (22/03/11) : add Thread to Connect a server\n");fct_send_line(soc,line);
sprintf (line, " v1.1  (23/03/11) : add Thread to listen a Connected Server \n");fct_send_line(soc,line);
sprintf (line, " v1.2  (24/03/11) : add re-routing fct \n");fct_send_line(soc,line);
sprintf (line, " v1.3  (24/03/11) : Can define the host connected (force) \n");fct_send_line(soc,line);
sprintf (line, " v1.4  (24/03/11) : Can send a Message to re-routed client \n");fct_send_line(soc,line);
sprintf (line, " v1.5  (25/03/11) : add help menu \n");fct_send_line(soc,line);
sprintf (line, " v2.0  (08/04/11) : add LPT port for LCD \n");fct_send_line(soc,line);
sprintf (line, " v2.1  (09/04/11) : pb end_line LCD:ok \n");fct_send_line(soc,line);
sprintf (line, " v2.2  (11/04/11) : Daemon mode (remove printf & scanf) \n");fct_send_line(soc,line);
sprintf (line, " v2.3  (11/04/11) : Protection INIT LTP \n");fct_send_line(soc,line);
sprintf (line, " v2.4  (11/04/11) : Modif Trace\n");fct_send_line(soc,line);
sprintf (line, " v2.5  (12/04/11) : Ajout Line2 3 et 4 to LCD\n");fct_send_line(soc,line);
sprintf (line, " v2.6  (13/04/11) : Ajout Thread RS232_read\n");fct_send_line(soc,line);
sprintf (line, " v2.7  (13/04/11) : Add listen_RS232 / stop\n");fct_send_line(soc,line);
sprintf (line, " v2.8  (13/04/11) : Modif RAW0 \n");fct_send_line(soc,line);
sprintf (line, " v2.9  (14/04/11) : New read RS232 (blocking) \n");fct_send_line(soc,line);
sprintf (line, " v3.0  (14/04/11) : Gestion locale de l HEURE \n");fct_send_line(soc,line);
sprintf (line, " v3.1  (15/04/11) : Thread RS232 broadcaste vers LCD__Server\n");fct_send_line(soc,line);
sprintf (line, " v3.2  (16/04/11) : Seul Thread HEURE parle a LCD (memo line)\n");fct_send_line(soc,line);
sprintf (line, " v3.2e (06/10/11) : Ameliore aide\n");fct_send_line(soc,line);
sprintf (line, " v3.2f (30/06/12) : Ajout HP/HC et cpt thread ds aide\n");fct_send_line(soc,line);
sprintf (line, " v3.2g (30/06/12) : Buffer RS en VAR globale + DEVICE=.....\n");fct_send_line(soc,line);
sprintf (line, " v4.0  (28/11/12) : Add Thread6 to listen /UNO=/dev/ttyACM0\n");fct_send_line(soc,line);
sprintf (line, " v4.1  (29/11/12) : Set GeoStatus (c j s l n t) in globale\n");fct_send_line(soc,line);
sprintf (line, " v4.2  (30/11/12) : protect send UNO if open\n");fct_send_line(soc,line);

}
//Globale 232

int wait_flag=TRUE;                     //TRUE while no signal received
char SerialDevice[80];
long Baud_Rate = 1200;          // default Baud Rate (110 through 38400)
long BAUD;                      // derived baud rate from command line
long DATABITS;
long STOPBITS;
long PARITYON;
long PARITY;
int Data_Bits = 7;              // Number of data bits
int Stop_Bits = 1;              // Number of stop bits
int Parity = 1;                 // Parity as follows:
                  // 00 = NONE, 01 = Odd, 02 = Even, 03 = Mark, 04 = Space
int Format = 5;
int NB_LI = 3;
int status;
int nb_lines=0;
int HEURE_enable=0;
int LCD_busy=0;
int HEUR_busy=0;

//====== EDF Globale Valeurs
int ADCO    =0;
int OPTARIF =1;
int ISOUSC  =2;
int HCHC    =3;
int HCHP    =4;
char PTEC[8]; // HP..  
int IINST1  =66;
int IINST2  =77;
int IINST3  =88;
int IMAX1   =9;
int IMAX2   =10;
int IMAX3   =11;
int PMAX    =12;
int PAPP    =13;
char HHPHC[8]; // A ,
int MOTDETAT=15;
int PPOT    =16;
//==fin Valeurs

//Globale
int ithread1;
int clients[MAXCLIENTS];
int reply_clients[MAXCLIENTS];
struct sockaddr_in adr_cli[MAXCLIENTS];
char global[MAXCLIENTS][MAXDATASIZE];
int size[MAXCLIENTS];
int j,h,m,s;
int nb_cli;
int ext_port;      //to_externe
char ext_adr[512]; //to_externe
int ext_req=0;     //to_externe
int ext_who=-1;    //to_externe
char to_ext_DATA[MAXDATASIZE]; //to_externe
int cli_sockfd=-1;
int cli_recv_data=0;
int cli_send_data=0;
int client_is_connected=-1;
int listen_LPT=-1;
int listen_RS=-1;
int listen_UNO=-1;
int nb_byte_LTP=0;
int RS_RAW=0;
int NB_Thread_tot,NB_Thread=0;
char memo_line1[128];
char memo_line2[128];
char memo_line3[128]; // memo LINE for LCD4x20
char memo_line4[128]; // memo LINE for LCD4x20
int soc_broad_232=-1;
char adr_broad_232[256]; 
int port_broad_232; 
int delta_us=0;
char indic_edf=' ';
char bufRS[255]; //read RS232

int fd_uno;  //Declare en Globale car itulise par le Write to send data to LCD4
int UNO_connected=0; // Carte UNO connectee
char memo_UNO[128];
char memo_UNO2[128];
char memo_GEO[128];
char memo_TH[128];
char global_UNO[16010];
int ptrW=0;

//Bonne sante des threads:
int i_thread_1=0; // *socket_function 
int i_thread_2=0; // *RS232_read
int i_thread_3=0; // *connect_client 
int i_thread_4=0; // *read_for_client
int i_thread_5=0; // *HEURE_auto 
int i_thread_6=0;
int i_Maxi=99999; // Maxi to reset



   int _0=1;
   int _1=2;
   int _2=4;
   int _3=8;
   int _4=16;
   int _5=32;
   int _6=64;
   int _7=128;

int aff=1;
//=======================================================================

int is(int val1){
   int ret;
//fprintf(stdout,"   -is %d\n",val1);
if(val1 > 0)  ret=1;
else      ret=0;

return ret;

}

//=======================================================================

send_raw(int val){

 outb(val, BASEPORT); //printf("outb\n");
 int VAL=val;
/***
if(aff == 1){
  fprintf(stdout,"    > [   ]");
  fprintf(stdout," . EN  - . RS - . .  . .  (x) \n");
  aff = 0;
}
 fprintf(stdout,"____> [%3d]", val);
        fprintf(stdout," %d  %d  - %d  %d - %d %d  %d %d  (x%x) %d\n", is(b8(VAL) )
                                                      , is(b7(VAL) )
                                                      , is(b6(VAL) )
                                                      , is(b5(VAL)) 
                                                      , is(b4(VAL) )
                                                      , is(b3(VAL))  , is(b2(VAL))  ,is(b1(VAL) ), VAL, VAL
);***/
  char line[2048];
  if (listen_LPT != -1 ) {
        sprintf(line,"____> [%3d]", val); fct_send_line(listen_LPT,line);
        sprintf(line," %d  %d  - %d  %d - %d %d  %d %d  (x%x) %d\n", is(b8(VAL) )
                                                      , is(b7(VAL))
                                                      , is(b6(VAL))
                                                      , is(b5(VAL)) 
                                                      , is(b4(VAL))
                                                      , is(b3(VAL))  
                                                      , is(b2(VAL))  
                                                      , is(b1(VAL)), VAL, VAL ); 
        fct_send_line(listen_LPT,line);


        

  } // send to LISTEN

 
  /* Sleep for a while (200 us) */
  usleep(200);
  //VAL= inb(BASEPORT );

        /*fprintf(stdout,"LPT: %d %d  - %d %d %d  - %d %d %d  (x%x) %d\n", is(b8(VAL) )
                                                      , is(b7(VAL) )
                                                      , is(b6(VAL) )
                                                      , is(b5(VAL)) 
                                                      , is(b4(VAL) )
                                                      , is(b3(VAL))  , is(b2(VAL))  ,is(b1(VAL) ), VAL, VAL
);*/


}
//=======================================================================

set___EN( int oct ){
   int EN=_6;
   send_raw( EN | oct) ; // Monte EN en plus de l octet deja envoye (pour le maintenir)
   usleep(1); //450 ns = 1us !!!
}
//=======================================================================

clear_EN( int oct, int mode ){
   int EN=_6;
   send_raw( oct) ; // renvoi l octet deja envoye (et donc EN=0)
   if (mode == CMD){
        usleep(5000); // 5 ms: CMD
   }else{
        usleep(200); // 200 us: DATA
   }

}
//=======================================================================

send_init( int   _4_bits ){
   send_and_tic(  _4_bits , CMD);
}

//=======================================================================

send_and_tic( int a_bit , int mode){

  int RS=_4;             //printf("RS\n");

  if (mode == DATA){        //
    a_bit = ( a_bit | RS ); // V2 : RS permanent
  }                         //

  send_raw(a_bit);         //printf("ra\n");
  set___EN( a_bit );       //printf("EN\n");
  clear_EN( a_bit , mode); //printf("/EN\n");


}
//=======================================================================

send_byte( int octet, int mode){
  //_______send_a_command___
  //send_and_tic(0, CMD); // Make sure EN=0 ! !! CC TO BE CONFIRM !!!!!

//______________________V1: RS non permanent___________
/*  if (mode == CMD){
        send_and_tic(0, CMD); // R/S=0 : CMD
  }else{
        send_and_tic(_4, CMD); // R/S=1 : DATA
  }*/

//______________________V2: RS permanent_OK_?___________
//
// Fait ds tic avec "| RS"

  send_and_tic( msb(octet), mode ); //Put the HIGH BYTE of the data/command on D7-4
  send_and_tic( lsb(octet), mode ); //Put the LOW BYTE of the data/command on D7-4
  nb_byte_LTP++;

}

//=======================================================================
send_DATA( int octet){
     
     printf(" %c :\n",octet);
     
        if (listen_LPT != -1) {
           char line[2048];
           sprintf (line, " %c :\n",octet ); //printf("li\n");
           fct_send_line(listen_LPT,line);   //printf("se\n");
        }
     send_byte(  octet, DATA); //printf("by\n");
}
//=======================================================================
send_CMD( int octet){
     send_byte(  octet, CMD);
}
//=======================================================================

send_STR(char * chaine){

int i;
int MAX=1024;
printf("STR = %s\n", chaine);
for (i=0; i<MAX; i++){
    if (chaine[i]==0) break;
    //printf("   i : %d  = %c (%d)\n", i, chaine[i], chaine[i]);  //DEBUG
     send_DATA( chaine[i] );
  }
//printf(" _____STR__END: send %d char.\n", i);  // DEBUG
printf(" __STR__END: %d char sent.\n", nb_byte_LTP); 

}
//=======================================================================

int  inBit(int in){
     // 9 = 00001001
     //     |.|.8421  
     //  128 32.
     //    64 16
 
   int res=0;
   int k,puis=1,dix=1;
   for (k=0 ; k<8 ; k++){
      
       res = res + (in & puis)/puis*dix;
       //printf(" p = %d\n", puis);
       
       puis=puis*2; // X 2
       dix = dix*10;
   }
   //printf(" res =%d\n",res);
   return res;

}
//=======================================================================

// 01 - Clear Display and Home the Cursor
// 10 - Return Cursor and LCD to Home Position

Clear_Home(void){
  printf("\n___Clear Display and Home the Cursor___\n");
  send_CMD( 0x01 );

}

LCD_Home(void){
  printf("\n___Return Cursor and LCD to Home Position___\n");
  send_CMD( 0x02 );

}

Goto_Line(int linei){
  char line[2048];
  sprintf (line, "\n___Goto_Line__%d__\n",linei );printf("%s", line);
  if (listen_LPT != -1) fct_send_line(listen_LPT,line);
 

  if (linei == 1)   send_CMD( 0x80 );
  if (linei == 2)   send_CMD( 0xC0 );
  if (linei == 3)   send_CMD( 0x94 );
  if (linei == 4)   send_CMD( 0xD4 );

}



//====================================================================
void fct_send_line(int soc, char* data){

   if (soc < 1 ) {  //ce n est pas un socket
        printf("%s",data);
   }else{
        send(soc,data,strlen(data),MSG_NOSIGNAL);
   }
}
//====================================================================
void init_LCD_hard(char* mess_init){

         /* Get access to the ports */
        if (ioperm(BASEPORT, 3, 1)) {perror("ioperm"); exit(1);}
  
         /* Set the data signals (D0-7) of the port to all low (0) */
send_init( 0 );
send_init( 1 );
send_init( 0 );
send_init( 0 );
send_init( 1 );


        printf("__Force LCD 8 bits__\n");
        aff=1;
        send_init( 3 );
        usleep(5000); // 5 ms !
        send_init( 3 );
        send_init( 3 );
        usleep(5000); // 5 ms !
        printf("\n\n");

        printf("__Passage 4 bits__\n");
        aff=1;
        send_init( 02 );  //ok
        //send_init( 0 );
        //send_CMD( 0x20 );
        printf("\n\n");


        /*
        R/S  R/W  D7  D6  D5  D4  D3  D2  D1  D0  Instruction/Description
        0    0    0   0   1   DL  N   F   *   *         Set Interface Length
        0    0    0   0   1   0   1   0   0   0 
         Set Interface Length = 
         DL - Set Data Interface Length 8(1)/4(0)
         N - Number of Display Lines 1(0)/2(1)
         F - Character Font 5x10(1)/5x7(0) */

        printf("__Passage 4 bits; 2 lines; 7 pix __\n");
        aff=1;
        //send_init( 2 );
        //send_init( 8 );
        send_CMD( 0x28 );
        printf("\n\n");
        //2h, 8h : mode 4 bits, 2 lignes, caractères 5x7 (28h)



        //    * 0h, Ch : affichage en fonction, pas de curseur (0Ch)
        printf("__aff ok, pas de curseur __\n");
        aff=1;
        send_CMD( 0x0C );
        printf("\n\n");

        printf("__increment curseur a droite apres 1 char __\n");
        aff=1;
        send_CMD( 0x06 );
        printf("\n\n");

        printf("__send INIT OK. __\n");
        Clear_Home();   
        send_STR( mess_init ); //"Init OK."

       // fin init
}
//====================================================================
void fct_LCD(int soc, char* buf){

        char line[2048];
        char lcd[16];
        char cmd[256];
        char arg1[256];
        char arg2[256];
        int i;
        int nb_bl=0; //nombre de blanc trouve
        int cmdi=0;
        int argi=0;

         /* Get access to the ports */
        int iop = ioperm(BASEPORT, 3, 1) ;


        sprintf (line, " LCD Mode. (ioperm = %d)\n", iop);fct_send_line(soc,line);
        if (iop){
                printf("ioperm FATAL ERROR : %d\n", iop);
                exit(1);
        }




        // sscanf(buf,"%s%s%s", lcd, cmd, arg1, arg2); // getline
        for(i=0; i< 2000; i++){
                //printf("%d:",i);
                //printf("%d - %c - %x\n",buf[i],buf[i],buf[i] );
                if (nb_bl == 1 ){ // rech cmd
                        cmd[cmdi]=buf[i]; cmdi++;
                }
                if (nb_bl >= 2 ){ // rech arg1
                        arg1[argi]=buf[i]; argi++;
                }


                if (buf[i] == ' ') { 
                        nb_bl++;
                        cmd[cmdi]=0;
                        arg1[argi]=0; // sera ecrase par le new CHAR reel
                        
                        
                }
                if (buf[i]==13) { break; }
                if (buf[i]==10) { break; }

        }
        arg1[argi-1]=0;

        printf("cmd: %s [%d bytes total]\n", cmd, i);
        printf("arg: [%s]\n", arg1);

        sprintf (line, " RCV: [%s] with arg: [%s]\n", cmd, arg1);fct_send_line(soc,line);

        if (listen_LPT != -1 ) {fct_send_line(listen_LPT,line);} // send to LISTEN

  if (strncmp (cmd, "init", 4) == 0) {
        sprintf (line, " send init. \n");fct_send_line(soc,line);
        init_LCD_hard( "Init OK." );
  } // if init____

  if (strncmp (cmd, "heure", 5) == 0) {
        HEURE_enable=atoi(arg1);
        sprintf (line, " Set Heure auto to %d.\n",HEURE_enable);fct_send_line(soc,line);
  } // if heure____


  if (strncmp (cmd, "send", 4) == 0) {
        sprintf (line, " send %d to LCD. \n",atoi(arg1) );fct_send_line(soc,line);
        send_CMD( atoi(arg1) );
  } // if send____

  if (strncmp (cmd, "str_send", 8) == 0) {
        nb_byte_LTP=0;
        //Clear_Home(); 
        Goto_Line(1);
        send_STR( arg1 );
        sprintf (line, " %d bytes sent to LCD. \n",nb_byte_LTP );fct_send_line(soc,line);
        if (listen_LPT != -1) fct_send_line(listen_LPT,line);
  } // if send____

  if (strncmp (cmd, "line:", 5) == 0) {   //line:1  line:2 ....line:4
        char li[3];
        li[0]=cmd[5]; li[1]=0;  // line = 1,2...
     //on memorise aussitot
        nb_byte_LTP=0;
        if ( atoi(li) == 1 ) sprintf(memo_line1,"%s",arg1); //Memorisation LINE:1 (pour HEURE auto)
        if ( atoi(li) == 2 ) sprintf(memo_line2,"%s",arg1); //Memorisation LINE:2 (pour EDF auto)

     LCD_busy=1; //usleep(50000); //50 ms
     usleep(1000) ; //attente du basculement du booleen HEUR_busy
        int j;
        for (j=0; j < 500 ; j++) {
           if(HEUR_busy ==1) { printf("#### LCD is Busy : Wait 1 ms more ... ####\n"); usleep(1000) ; }
           if(HEUR_busy ==0) break;
        }
        //Clear_Home();//Ne plus faire ici !!
        // MEMO// Goto_Line( atoi(li) );
        // MEMO// send_STR( arg1 );
        //old sprintf (line, " %d bytes sent to LCD_memo.   [Wait %d]\n",nb_byte_LTP, j );fct_send_line(soc,line);
        sprintf (line, " %d bytes sent to LCD_memo.   [Wait %d]\n",strlen(arg1), j );fct_send_line(soc,line);
        if (listen_LPT != -1) fct_send_line(listen_LPT,line);
      usleep(3000);
      LCD_busy=0; 

  } // if send____


  if (strncmp (cmd, "hexa_send", 9) == 0) {
        sprintf (line, " send %s to LCD. \n",arg1 );fct_send_line(soc,line);
        // Ox0c
        //   A2  = a * 16 + 2 = 162
        int m=arg1[0] - 48;
        int l=arg1[1] - 48;
        if(m > 48) m=m-49+10;
        else if(m > 16) m=m-17+10;

        if(l > 48) l=l-49+10;
        else if(l > 16) l=l-17+10;

        //int M=atoi((char) m);
        //int L=atoi((char) l);
        int ML = m * 16 + l;

        
        sprintf (line, " send %d (0x%02x) to LCD. %d %d\n",ML , ML, m, l);fct_send_line(soc,line);
        send_CMD( ML );
  } // if send____

}
//====================================================================
void fct_LCD_multi(int soc, char* buf, int bytes){

        char line[2048];
        int i,j=0;

        for(i=0;  i< bytes ; i++ ){
                line[j]=buf[i]; j++;//printf("%c", buf[i]);
                if (buf[i]==10) 
                {
                        line[j]=0; //end str
                        printf ("  LCD_m: ONE line found:[%s]\n", line);
                        fct_LCD(soc, line);
                        j=0; //reset line
                }
        }//for i

}
//====================================================================
int send_1_line(int Li, char* datas){

        char line[2048];
        int Lng = strlen(datas);
        int Nb_w;
        int ret=-2;
      
        if ( Li >= 0 ){
          if ( Li < 4 ){
          
              if (UNO_connected){ 

                 sprintf(line, "%d%s%c", Li, datas, 92); // = 1: titi\"
                 Nb_w = write(fd_uno,&line,Lng+3); //+3 = 1:  et  \
              
                 if (Li==0) sprintf( memo_line1, "%s /%d", datas, Nb_w); 
                 if (Li==1) sprintf( memo_line2, "%s /%d", datas, Nb_w); 
                 if (Li==2) sprintf( memo_line3, "%s /%d", datas, Nb_w); 
                 if (Li==3) sprintf( memo_line4, "%s /%d", datas, Nb_w);
                 ret=Nb_w; 
              
              }
              else{
                 ret=-1;
              }
                 
            }
          }
          return ret;

}

//====================================================================
void fct_LCD4_multi(int soc, char* buf, int bytes){


        char cmd[128];
        char chaine[128];
        char line[256];
        
        int Li;
        int i,j=0;
        int Bytes;

         //rcv:   "LCD4: 1: titi"

            //printf ("  LCD4: ONE line found:[%s]\n", buf);
                        
            sscanf(buf, "%s %d %s", &cmd, &Li, &chaine);
            for (i=8; i<128; i++){
               chaine[j]=buf[i]; j++;
               if (buf[i]==0) { break; }
            } 

            printf ("  LCD4: cmd=%s / Li=%d / ch=%s\n", cmd, Li, chaine);
            //chaine[Lng]=92; // =\
            //chaine[Lng+1]=0;
            
            Bytes=send_1_line( Li, chaine ); // Send 1 line to LCD4 
            if (Bytes > 0){
               sprintf (line, "%d bytes sent to LCD. \n",Bytes );fct_send_line(soc,line);
            }else{
               sprintf (line, "ERROR %d (send to LCD). \n",Bytes );fct_send_line(soc,line);
            }     
      

}
//====================================================================
void print_UNO(int soc){

   int j;
   char bu[2];
   int max=16000;
   if (max > ptrW) max=ptrW;

   printf ("\n______RCV__UNO_______:\n\n");
   
   for (j=0; j<max; j++) {
   
      if (soc < 1 ) {  //ce n est pas un socket
        printf ("%c",    global_UNO[j]);
      }else{
        bu[0]=global_UNO[j];
        bu[1]=0;
        send(soc,bu,1,MSG_NOSIGNAL);
      }

      

   }
   printf ("\n xxxxxxxxxxxxxxxxxxxxxxxxxx \n");

}
//====================================================================
void connecte_broadcast(){

 //deb conn
    int  n;
    struct sockaddr_in serv_addr;
    struct hostent* server;
    char bufbroad[256];

    soc_broad_232 = socket(AF_INET, SOCK_STREAM, 0);
    if (soc_broad_232 < 0) 
        printf("ERROR opening socket Broadcast 232\n");
    else
        printf("Socket Broadcast 232 opened.\n");

    server = (struct hostent*) gethostbyname(adr_broad_232); //ext 232
    if (server == NULL) {
        printf("ERROR, no such host : %s\n", adr_broad_232);
        soc_broad_232 = -1;
       
    }else{
            printf("Found host : %s\n", adr_broad_232);
            bzero((char *) &serv_addr, sizeof(serv_addr));
            serv_addr.sin_family = AF_INET;
            bcopy((char *)server->h_addr, 
                 (char *)&serv_addr.sin_addr.s_addr,
                 server->h_length);
            serv_addr.sin_port = htons(port_broad_232); // ext 232

        //________________Connect_______
        if (connect(soc_broad_232,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0){ 
                printf("ERROR connecting %s; wait 3 s...\n", adr_broad_232);
                sleep(3);
                //soc_broad_232=-1;
        }else{

          sprintf(bufbroad,"Je suis Broadcast EDF.\n");   
          n = send(soc_broad_232,bufbroad,strlen(bufbroad),MSG_NOSIGNAL);
          if (n < 0) 
            printf("ERROR writing to socket %d (@%d)\n", soc_broad_232,port_broad_232);
          else
            printf("Send %d bytes : %s\n", n, bufbroad);


          bzero(bufbroad,256);
          n = read(soc_broad_232,bufbroad,255);
          if (n < 0) 
             printf("ERROR reading from socket %d (@%d)\n", soc_broad_232,port_broad_232);
          else
             printf("Broadcast connected [%d bytes rcv]: %s\n", n, bufbroad);
        }//if connect

    //ask_for_reply(1);
    //send(soc_broad_232, to_ext_DATA,strlen(to_ext_DATA),MSG_NOSIGNAL);  
    //printf("%s\n",buffer);
   }//if Host found
   //fin conn
}

//====================================================================
void fct_RS_broadcast(int soc, char* buf){

  char cmd[256]; 
  char arg[256]; 
  int ret;                                                        // broad: OFF / 0
  
  sscanf(buf, "%s %s %d", &cmd, &arg, &port_broad_232); // broad: pclin2 8811

  printf(" REQ Boardcast vers : %s  %d\n", arg, port_broad_232);


  if (strncmp (arg, "OFF", 3) == 0) {
        ret=close(soc_broad_232); usleep(2000);printf("soc %d close ? ret=%d\n",soc_broad_232,ret);
        ret=close(soc_broad_232); printf("ret=%d\n",ret);
        
        soc_broad_232 = -1;
        printf(" REQ Boardcast OFF.  ret=%d\n",ret);

  }else if(strncmp (arg, "iii", 3) == 0){
        sscanf(buf, "%s %s %d %d %d %c", &cmd, &cmd, &IINST1, &IINST2, &IINST3 ,&indic_edf);
        printf("III= %d %d %d\n",IINST1, IINST2, IINST3);
  }else{

  sprintf(adr_broad_232,"%s",arg);
  connecte_broadcast();

 }//if Broad


}
//====================================================================
void fct_RS(int soc, char* buf){

        char line[2048];   // RS232: H* 1  (1 est obligatoire, ou N)
        char lcd[16];
        char cmd[256];
        char arg1[256];
        char arg2[256];
        int i;
        int nb_bl=0;
        int cmdi=0;
        int argi=0;


        sprintf (line, " RS232 fct.\n");fct_send_line(soc,line);

        // sscanf(buf,"%s%s%s", lcd, cmd, arg1, arg2); // getline
        for(i=0; i< 2000; i++){
                //printf("%d:",i);
                //printf("%d - %c - %x\n",buf[i],buf[i],buf[i] );
                if (nb_bl == 1 ){ // rech cmd
                        cmd[cmdi]=buf[i]; cmdi++;
                }
                if (nb_bl >= 2 ){ // rech arg1
                        arg1[argi]=buf[i]; argi++;
                }


                if (buf[i] == ' ') { 
                        nb_bl++;
                        cmd[cmdi]=0;
                        arg1[argi]=0; // sera ecrase par le new CHAR reel
                        
                        
                }
                if (buf[i]==13) { break; }
                if (buf[i]==10) { break; }

        }
        arg1[argi-1]=0;

        printf("cmd: %s [%d bytes total]\n", cmd, i);
        printf("arg: [%s]\n", arg1);

        sprintf (line, " RCV: [%s] with arg: [%s]\n", cmd, arg1);fct_send_line(soc,line);

        int bb, BCL=120;
        int nb_bcl = atoi(arg1);
        if (nb_bcl > BCL) nb_bcl=BCL;
        if (nb_bcl > 0) {
           for(bb=0; bb<nb_bcl; bb++){

  if (strncmp (cmd, "HP", 2) == 0) { sprintf(line, "HP= %d\n", HCHP);fct_send_line(soc,line); } 
  if (strncmp (cmd, "HC", 2) == 0) { sprintf(line, "HC= %d\n", HCHC);fct_send_line(soc,line); } 
  if (strncmp (cmd, "H*", 2) == 0) { sprintf(line, "HP= %d ;HC= %d\n", HCHP, HCHC);fct_send_line(soc,line); } 

  if (strncmp (cmd, "I*", 2) == 0) {
         sprintf (line, "I1= %d ;I2= %d ;I3= %d \n", IINST1, IINST2, IINST3 );fct_send_line(soc,line);
        } 
     if (nb_bcl > 1 ) sleep(1);
     }//for bb
   }//if nb >0
  if (strncmp (cmd, "RAW1", 4) == 0) {RS_RAW=1; sprintf(line, "RAW Mode OK. RAW0 to STOP\n");fct_send_line(soc,line); } 
  if (strncmp (cmd, "RAW0", 4) == 0) {RS_RAW=0; sprintf(line, "RAW Mode STOP.\n");fct_send_line(soc,line); } 
}
//====================================================================
void fct_UNO(int soc, char* buf){

   //UNO: GET Geo/Temp/All
   //UNO: SET Moy 7 : nb measure for Geo position

    char line[2048];
    char uno[16];
    char cmd[16];
    char arg[64];
    
    int pb=1;
    
    sprintf (line, " UNO fct.\n");fct_send_line(soc,line);
   
    sscanf(buf,"%s %s %s", uno, cmd, arg); // getline
    
    if (strncasecmp (cmd, "GET", 3) == 0) {
    
      if (strncasecmp (arg, "Geo", 3) == 0) {
         sprintf(line, "%s \n", memo_GEO); fct_send_line(soc,line); pb=0;
      }
      
      if (strncasecmp (arg, "Temp", 4) == 0) {
         sprintf(line, "%s \n", memo_TH); fct_send_line(soc,line); pb=0;
      }
       
    } 
    if (strncasecmp (cmd, "SET", 3) == 0) {
       // to do !!!!
    }
    
    if (pb) {sprintf(line, "NOT_UNDERSTAND : %s \n", buf); fct_send_line(soc,line); }


}
//====================================================================
void fct_help(int soc){

      char line[2048];


sprintf (line, "\n_________________HELP_______________________%s_______\n",VERSION);fct_send_line(soc,line);
sprintf (line, " status      : Disply the status of TCP server \n");fct_send_line(soc,line);
sprintf (line, " reply       : Toggle in reply mode \n");fct_send_line(soc,line);
sprintf (line, " stop_reply  : Stop reply mode \n");fct_send_line(soc,line);
sprintf (line, " help        : Display this message \n");fct_send_line(soc,line);
sprintf (line, " hist        : Display historique \n");fct_send_line(soc,line);
sprintf (line, " exit        : exit client connexion \n");fct_send_line(soc,line);
sprintf (line, " listen_LPT  : listen Data send to LPT \n");fct_send_line(soc,line);
sprintf (line, " listen_RS   : listen Data recv from RS232 \n");fct_send_line(soc,line);
sprintf (line, " listen_UNO  : listen Data recv from /UNO RS232 \n");fct_send_line(soc,line);
sprintf (line, " stop        : Stop listen mode (LPT or RS or UNO) \n");fct_send_line(soc,line);
sprintf (line, " STOP_SERVER : STOP the Daemon SLP !!\n");fct_send_line(soc,line);

sprintf (line, " LCD: init/send ASC/hexa_send FF      : to LPT \n");fct_send_line(soc,line);
sprintf (line, " LCD: line:1 titi/heure 0/heure 1     : to LPT \n");fct_send_line(soc,line);
sprintf (line, " RS232: HP/HC/H*/I*/RAW0/RAW1         : Cpt EDF \n");fct_send_line(soc,line);
sprintf (line, " broad: OFF/pclin2 8811               : Broadcast EDF auto.\n");fct_send_line(soc,line);
sprintf (line, " LCD4: 1:TITI  (LCD4: K)    : Send TITI on line -1- on LCD4x20.\n");fct_send_line(soc,line);
sprintf (line, " UU                         : get RCV buffer from UNO.\n");fct_send_line(soc,line);
sprintf (line, " UNO: GET Geo/Temp/All      : Get Geo or Temp buffer from UNO.\n");fct_send_line(soc,line);

}
//====================================================================
void fct_status_soc(int soc, int mode){

  /* Mode = 0 : ASCII only
          = 1 : Binaire only
          = 2 : ALL
              */
      int i,k;  //send(new_fd,"Welcome ! ",10,MSG_NOSIGNAL);
      char line[2048];

/*
int nb_cli;
int ext_port;      //to_externe
char ext_adr[512]; //to_externe
int ext_req=0;     //to_externe
int ext_who=-1;    //to_externe
char to_ext_DATA[MAXDATASIZE]; //to_externe
int cli_sockfd=-1;
int cli_recv_data=0;
int cli_send_data=0; */

sprintf (line, "\n__________________VAR________________________________\n");fct_send_line(soc,line);
sprintf (line, "|   nb_client = %d \n", nb_cli );fct_send_line(soc,line);
sprintf (line, "|    ext_port = %d      | NB_Thread=%d\n", ext_port ,NB_Thread );fct_send_line(soc,line);
sprintf (line, "|     ext_adr = %s      | i_thread_1:%d\n", ext_adr       ,i_thread_1 );fct_send_line(soc,line);
sprintf (line, "|     ext_who = %d      | i_thread_2:%d\n", ext_who       ,i_thread_2 );fct_send_line(soc,line);
sprintf (line, "|  cli_sockfd = %d      | i_thread_3:%d\n", cli_sockfd    ,i_thread_3 );fct_send_line(soc,line);
sprintf (line, "|soc_broad_232= %d      | i_thread_4:%d\n", soc_broad_232 ,i_thread_4 );fct_send_line(soc,line);
sprintf (line, "|  listen_LPT = %d      | i_thread_5:%d\n", listen_LPT    ,i_thread_5 );fct_send_line(soc,line);
sprintf (line, "|  listen_RS  = %d      | i_thread_6:%d \n", listen_RS    ,i_thread_6 );fct_send_line(soc,line);
sprintf (line, "(HEUR)delta_us= %d \n", delta_us );fct_send_line(soc,line);

sprintf (line, "|................__EDF__................\n");fct_send_line(soc,line);
sprintf (line, "| HP = %d / HC = %d / Puis = %d / inst = %d %d %d\n\n", HCHP, HCHC, PAPP, IINST1, IINST2, IINST3);fct_send_line(soc,line);


sprintf (line, "|................__LCD4__...............\n");fct_send_line(soc,line);
sprintf (line, "|  LINE1: %s \n", memo_line1  );fct_send_line(soc,line);
sprintf (line, "|  LINE2: %s \n", memo_line2  );fct_send_line(soc,line);
sprintf (line, "|  LINE3: %s \n", memo_line3  );fct_send_line(soc,line);
sprintf (line, "|  LINE4: %s \n", memo_line4  );fct_send_line(soc,line);

sprintf (line, "|  GEO: %s \n", memo_GEO  );fct_send_line(soc,line);
sprintf (line, "|  TH : %s \n", memo_TH   );fct_send_line(soc,line);
sprintf (line, "|  UNO: %s [rcv %d]\n", memo_UNO2 ,ptrW );fct_send_line(soc,line);
sprintf (line, "|  UNO: %s \n", memo_UNO   );fct_send_line(soc,line);

sprintf (line, "|  RS232: %s: %s \n", SerialDevice, bufRS  );fct_send_line(soc,line);

      sprintf(line,"______Clients__Connected_:_%d_____%dj_%02d:%02d:%02d__up_____\n",nb_cli,j,h,m,s);
      fct_send_line(soc,line);

      for ( i = 0 ; i < MAXCLIENTS ; i ++ ) {
         if ( clients[i] != 0 ) {
            sprintf (line, " %d: %d  %s", i, clients[i], inet_ntoa(adr_cli[i].sin_addr));
            fct_send_line(soc,line);
            sprintf (line, "  %s   ",global[i]);  //last message sent for this client
            fct_send_line(soc,line);
          if (mode > 0 ) {
            for( k=0; k< size[i]; k++){
                sprintf (line, "x%02x ",global[i][k]);
                fct_send_line(soc,line);
            }
            sprintf(line, "\n");
            fct_send_line(soc,line);
          } // if mode
         } //if cli != 0
      } // for
sprintf (line, "\n_____________________________________________________\n");fct_send_line(soc,line);

}
//====================================================================
void fct_STOP_SVR(int soc){

      char line[2048];


sprintf (line, "\n__STOP_SERVER_NOW__\n");fct_send_line(soc,line);
ithread1 = 0;

}
//====================================================================
void fct_listen_LPT(int soc){

      char line[2048];

printf(" LISTEN soc = %d \n", soc);
sprintf (line, "\n__Listen_LPT_Mode_OK__\n");fct_send_line(soc,line);
listen_LPT = soc;

}
//====================================================================
void fct_listen_RS(int soc){

      char line[2048];

printf(" LISTEN RS232 soc = %d \n", soc);
sprintf (line, "\n__Listen_RS232_Mode_OK__\n");fct_send_line(soc,line);
listen_RS = soc;

}
//====================================================================
void fct_listen_UNO(int soc){

      char line[2048];

printf(" LISTEN UNO RS232 soc = %d \n", soc);
sprintf (line, "\n__Listen_UNO_RS232_Mode_OK__\n");fct_send_line(soc,line);
listen_UNO = soc;

}
//====================================================================
void fct_listen_RS_STOP(int soc){

      char line[2048];

printf(" LISTEN ALL soc = %d STOP\n", soc);
sprintf (line, "\n__Listen_ALL_Mode_STOP__\n");fct_send_line(soc,line);
listen_RS  = -1;
listen_LPT = -1;
listen_UNO = -1;

}
//====================================================================
void req_connect(char* adrr, int iport, int from_who){

printf("req_connect: start...");
  ext_port=iport;               //to_externe
  sscanf(adrr,"%s", ext_adr) ;  //to_externe
  ext_who=from_who;             //to_externe
  ext_req=1;                    //to_externe

printf("req_connect: end.\n");
}


//=======================================================================
//=======================================================================
//=====                                                           =======
//=====                 M   A   I   N                             =======
//=====                                                           =======
//=======================================================================
//=======================================================================


int main(int argc, char *argv[])
{
     printf("Start SLP Main %s...  (argc=%d)\n",VERSION, argc);     
     char *status ="Start...";
     int aff=1;
     char clavier[32];
     s=0;m=0;h=0;j=0;
     
     //LCD: init
     sprintf(memo_line1,"------"); //init LINE:1  
     sprintf(memo_line2,"______"); //init LINE:2 
     sprintf(memo_UNO ," ");
     sprintf(memo_UNO2," ");
     sprintf(memo_GEO,"Geo: 00 00 00 00 00 00  NEVER_GET");
     sprintf(memo_TH ,"Temp: 88 77 - - - -  NEVER_GET");
     


     if (argc < 2) {
         fprintf(stderr,"\nUsage: SLP <port> <-h/noh> [-daemon/no] [/dev/ttyS0]\n\n");
         fprintf(stderr,"         8232      : server IP port \n");
         fprintf(stderr,"         -h        : heure automatic to LCD or not\n");
         fprintf(stderr,"         -daemon   : Main menu on/off\n");
         fprintf(stderr,"         /dev/ttyS0: device RS232\n\n\n");
         exit(1);
     }
   

     pthread_t thread1, thread2, thread3, thread4, thread5, thread6;

     char port_IP_svr[64];
     char *message2 = "9999";
     char *message3 = "3";
     char *message4 = "stop";
     char *message5 = "heure";
     char *message6 = "UNO_rs";
     char mode[32];
     int tmp1;
     sprintf(memo_line1," --      ");//init
     sprintf(memo_line2," ++      ");//init

     int  iret1, iret2, iret3, iret4, iret5, iret6;
     sprintf(port_IP_svr,"%s",argv[1]);  // int portno = atoi(argv[1]);
     //sprintf(message1,"%s",message2);  // int portno = atoi(argv[1]);
 
  

    //a suppr en mode DAEMON

//----------------------------------------    
// SLP 8232 -noh  [-daemon]
//  1   2     3      4

if(argc >= 3) sprintf(mode,"%s",argv[2]); // -h -noh
if (strncmp (mode, "-h", 2) == 0) HEURE_enable=1;
if (strncmp (mode, "-noh", 4) == 0) HEURE_enable=0;

// si pas HEURE, on gere le daemon en 3eme posi
if (strncmp (mode, "-nodaemon", 9) == 0) {sprintf(mode,"-nodaemon");}
else sprintf(mode,"-daemon");

// Si 3 argument : c est forcement le daemon
if(argc >= 4) sprintf(mode,"%s",argv[3]); // -nodaemon

//----------------------------------------    
// SLP 8232 -noh  -daemon /dev/ttyS0
//  1   2     3      4       5
if(argc == 5) sprintf(SerialDevice,"%s",argv[4  ]); // Device RS232
else sprintf(SerialDevice,"%s",devicename); //tjs = /dev/ttyS0
printf("  (device= %s)\n", SerialDevice);  

    /* Create independent threads each of which will execute function */
 
     printf("Start Thread 1 with arg = %s\n", port_IP_svr);
     ithread1=1;
     NB_Thread_tot=6;
     iret1 = pthread_create( &thread1, NULL, *socket_function, (void*) port_IP_svr);
     //iret2 = pthread_create( &thread2, NULL, socket_function, (void*) message2);// 9999
     iret2 = pthread_create( &thread2, NULL, *RS232_read, (void*) message2);

     iret3 = pthread_create( &thread3, NULL, *connect_client, (void*) message3);
     iret4 = pthread_create( &thread4, NULL, *read_for_client, (void*) message4);
     iret5 = pthread_create( &thread5, NULL, *HEURE_auto,   (void*) message5);
     iret6 = pthread_create( &thread6, NULL, *UNO_read_non_blocking,(void*) message6);     
//i_thread_5++; if(i_thread_5 > i_Maxi) i_thread_5=3; //verifie la bonne sante des thread (visible dans status)
     usleep(50000); // 50 ms      


printf(" Mode : %s.\n", mode);  

if (strncmp (mode, "-nodaemon", 9) == 0){
    int imain=1; //ARRET PROGRAMME
        char *ccc;
        time_t mytime;
        
        //printf(ctime(&mytime));


    while (imain){
    mytime = time(NULL);
    printf("\n +----------------------+     ");   printf(ctime(&mytime));
    printf(" |   Main MENU  %s  |\n",VERSION);  
    printf(" +----------------------+\n"); 
    printf(" s : Status                       ( %d connected)\n", nb_cli);  
    printf(" 2 : Status  ASC+BIN \n");  
    printf(" f : force ext_who\n");  
    printf(" t : toto sent to client 1\n");  
    printf(" h : help\n");  
    printf(" v : Version Historique\n");  
    printf(" U : rcv buffer UNO\n");  
    printf(" q : Quit TCP server   @%d   (%d %d %d) (%c%c%c)\n", atoi(port_IP_svr), clavier[0], clavier[1],clavier[2],
                                clavier[0], clavier[1],clavier[2]);  


    bzero(clavier,32);
    usleep(150000); //150 ms
    fgets(clavier,31,stdin);

    if (clavier[0] == 'q') imain=0;
    if (clavier[0] == 's') fct_status_soc(-1, 0); // -1 car printf ds stdin !
    if (clavier[0] == '2') fct_status_soc(-1, 2); // -1 car printf ds stdin !
    if (clavier[0] == 'h') fct_help(-1); // -1 car printf ds stdin !
    if (clavier[0] == 'v') fct_hist(-1); // -1 car printf ds stdin !
    if (clavier[0] == 'U') print_UNO(-1); // -1 car printf ds stdin !
    if (clavier[0] == 't'){
         tmp1 = send(ext_who, "toto from MAIN !\n",17,MSG_NOSIGNAL);
         if (tmp1 <= 0) printf("Cannot send toto to client !!!!\n\n");
    }
    if (clavier[0] == 'f'){
         printf("New value (%d) for ext_who ? ",  ext_who);
         fgets(clavier,31,stdin);
         sscanf(clavier,"%d", &ext_who);

    }



    }//while

    printf("M: Waiting thread 1 stop...\n"); 
    ithread1=0;
}//if nodaemon

    pthread_join( thread1, NULL);
    pthread_join( thread2, NULL);
    pthread_join( thread3, NULL);
    pthread_join( thread4, NULL);
    pthread_join( thread5, NULL);
    pthread_join( thread6, NULL);
    printf("Main STOP.\n");    

}

//====================================================================
//====================================================================
//====================================================================


void *socket_function( void *ptr )
{
   NB_Thread++; printf("...Thread %d/%d start(socket_function).\n", NB_Thread, NB_Thread_tot);
   
   int sockfd,new_fd,numbytes,highest = 0,i;
   //int clients[MAXCLIENTS];
   char buffer[MAXDATASIZE] ;

     char *str_port;
     str_port = (char *) ptr;
     int portno = atoi(str_port);
     int k,ms=0;



   struct sockaddr_in my_addr, their_addr;
   socklen_t sin_size;
   struct timeval tv;
   fd_set readfds;

   if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
     perror("socket");
     exit(-1);
   }
   my_addr.sin_family = AF_INET;       
   my_addr.sin_port = htons(portno); // htons(MYPORT);  //serv_addr.sin_port = htons(portno);
   my_addr.sin_addr.s_addr = INADDR_ANY;
   bzero(&(my_addr.sin_zero), 8);

   if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
      perror("bind");
      exit(-1);
   }
   printf("Server on port %d...",portno);//cc
   if (listen(sockfd, BACKLOG) == -1) {
      perror("listen");
      exit(-1);
   }
   printf("started.\n"); //cc
   bzero(clients,sizeof(clients));      // INIT = 0
   bzero(reply_clients,sizeof(clients));// INIT = 0

   highest = sockfd ;
   while(ithread1) {
      //printf("Th.");fflush(stdout); //cc
      //__cpt de temps que sur Thread 9999 (Supervision)
      if(portno != 9999){
              ms++;
              if(ms > 38) {ms=0; s++;}  // 40 X 25ms = 1s
              if(s > 59) {s=0; m++;}
              if(m > 59) {m=0; h++;}
              if(h > 23) {h=0; j++;}
      }

      sin_size = sizeof(struct sockaddr_in);     
      tv.tv_sec = 0;
      tv.tv_usec = 25000; // 25ms // int = 250 ms
      FD_ZERO(&readfds);
      nb_cli=0;
      for ( i = 0 ; i < MAXCLIENTS ; i ++ ) {
         if ( clients[i] != 0 ) {
            FD_SET(clients[i],&readfds);
            nb_cli++;
         }
      }
      FD_SET(sockfd,&readfds);  
      if (select(highest+1, &readfds, NULL, NULL, &tv) >=0 ) {
         if (FD_ISSET(sockfd, &readfds)) {
            if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) {
               perror("accept");
               continue;
            }
            for( i = 0 ; i < MAXCLIENTS ; i ++ ) {
               if ( clients[i] == 0 ) {
                  clients[i] = new_fd ;
                  adr_cli[i] = their_addr;
                  break;
               }
            }
            if ( i != MAXCLIENTS ) {
               if ( new_fd > highest ) {
                  highest = clients[i] ;
               }
               printf("Connexion received from %s (slot %i) \n",inet_ntoa(their_addr.sin_addr),i);
               send(new_fd,"Welcome ! ",10,MSG_NOSIGNAL);
            }    
            else {
               send(new_fd, "No room for you ! ",18,MSG_NOSIGNAL);
               close(new_fd);  
            }
         }
         for ( i = 0 ; i < MAXCLIENTS ; i ++ ) {
            if ( FD_ISSET(clients[i],&readfds) ) {
               if ( (numbytes=recv(clients[i],buffer,MAXDATASIZE,0)) <= 0 ) {
                  printf("\nConnexion lost from slot %i \n",i); 
                  if ( clients[i] == listen_LPT) { listen_LPT = -1; } // Fin Listen LPT
                  if ( clients[i] == listen_RS)  { listen_RS  = -1; } // Fin Listen_RS
                  if ( clients[i] == listen_UNO) { listen_UNO = -1; } // Fin Listen_UNO
                  close(clients[i]);
                  clients[i] = 0 ;
                  printf("  - listen_LPT = %i\n", listen_LPT);
                  printf("  - listen_UNO = %i\n", listen_UNO);
                  printf("  - listen_RS  = %i\n\n", listen_RS );

               }
               else {
                  buffer[numbytes] = 0; //  '\\0'
                  printf("Received from slot %i [%d bytes]: %s\n", i, numbytes, buffer);
                  for(k=0; k<numbytes; k++)
                    printf("x%02x ",  buffer[k]);
                  printf("\n");      



                  sprintf(global[i],"%s",buffer);
                  size[i] = numbytes;
                  //sortie d un client
                  if (strncmp (buffer, "exit", 4) == 0) {
                      send(clients[i], "Bye ! ",6,MSG_NOSIGNAL);
                      if ( clients[i] == listen_LPT) { listen_LPT=-1; }//Fin Listen LPT
                      if ( clients[i] == listen_RS)  { listen_RS =-1; }//Fin Listen_RS
                      if ( clients[i] == listen_UNO) { listen_UNO=-1; }//Fin Listen_UNO
                      close(clients[i]);
                      clients[i] = 0 ;
                      printf("Client slot %i exiting ! [soc=%d]\n", i, clients[i]);
                      printf("  - listen_LPT = %i\n", listen_LPT);
                      printf("  - listen_RS  = %i\n", listen_RS );
                      printf("  - listen_UNO = %i\n", listen_UNO);
                      
                   }
                  if (strncmp (buffer, "status", 6) == 0) { fct_status_soc(clients[i], 0); }
                  if (strncmp (buffer, "s", 1) == 0) { fct_status_soc(clients[i], 0); }   // Ajout s pour status en remote
                  if (strncmp (buffer, "help", 4) == 0) { fct_help(clients[i] ); }
                  if (strncmp (buffer, "hist", 4) == 0) { fct_hist(clients[i] ); }
                  if (strncmp (buffer, "listen_LPT", 10) == 0) { fct_listen_LPT(clients[i] ); }
                  if (strncmp (buffer, "listen_RS", 9) == 0) { fct_listen_RS(clients[i] ); }    
                  if (strncmp (buffer, "listen_UNO", 10) == 0) { fct_listen_UNO(clients[i] ); } 
                  if (strncmp (buffer, "stop", 4) == 0) { fct_listen_RS_STOP(clients[i] ); }
                  if (strncmp (buffer, "STOP_SERVER", 11) == 0) { fct_STOP_SVR(clients[i] ); }
                  if (strncmp (buffer, "LCD:", 4) == 0) { fct_LCD_multi(clients[i] , buffer, numbytes ); }
                  if (strncmp (buffer, "RS232:", 6) == 0) { fct_RS(clients[i] , buffer ); }
                  if (strncmp (buffer, "broad:", 6) == 0) { fct_RS_broadcast(clients[i] , buffer ); }

                  if (strncmp (buffer, "LCD4:", 5) == 0) { fct_LCD4_multi(clients[i] , buffer, numbytes ); }
                  
                  if (strncmp (buffer, "UU", 2)    == 0) { print_UNO(clients[i] ); }
                  if (strncmp (buffer, "UNO:", 4)  == 0) { fct_UNO(clients[i] , buffer ); }
                 

                  if (strncmp (buffer, "telnet", 6) == 0) { 
                   int iport; char cmd[256];char adrr[256];
                   sscanf(buffer, "%s %s %d", &cmd, &adrr, &iport);
                   printf(" REQ telnet vers : %s  %d\n", adrr, iport);
                   req_connect(adrr, iport, clients[i]);
                  }
                  if (cli_sockfd > 2) { //on est connecte au client2
                                        //on re-route les requetes :
                        
                        printf("re-routing from %d : [%d]: %s\n", clients[i], numbytes, buffer);

                  for(k=0; k<numbytes; k++)
                    printf("x%02x ",  buffer[k]);
                    

                        fflush(stdout);
                          //buffer[numbytes]='\n';  // Ajout de 2 CR !!!!
                          //buffer[numbytes+1]='\n';

                        int tmp3=send(cli_sockfd, buffer ,numbytes/* +2 */,MSG_NOSIGNAL);
                        //int tmp3=write(cli_sockfd, buffer ,numbytes);
                        
                         printf(" %d bytes sent.\n", tmp3);   
                  }
                  if (strncmp (buffer, "reply", 5) == 0) {
                      send(clients[i], "Reply activate.",15,MSG_NOSIGNAL);
                      reply_clients[i] = 1 ;
                      printf("Client slot %i in reply mode.\n", i);
                   }
                  if (strncmp (buffer, "stop_reply", 10) == 0) {
                      send(clients[i], "Reply desactivate.",18,MSG_NOSIGNAL);
                      reply_clients[i] = 0 ;
                      printf("Client slot %i STOP reply mode.\n", i);
                   }
                  if ( reply_clients[i] == 1) {
                      send(clients[i], buffer,strlen(buffer),MSG_NOSIGNAL);
                      
                      printf("Send back to slot %i : %s\n", i, buffer);
                   }

                  if (cli_recv_data > 0) {  //data arrives from client2
                        printf("DATA to cli_1 : [%d]: %s\n",cli_recv_data, to_ext_DATA);
                        fflush(stdout);
                        cli_recv_data = -1;
                        send(clients[i], to_ext_DATA,cli_recv_data,MSG_NOSIGNAL);
                  }
                 
               } //if num
            }  // if FD
         }  //for i
      } // select
      else {
         perror("select");
         continue;
      }

   //__verrue__ds__bcle__main
          if (cli_recv_data > 0) {  //data arrives from client2
                printf("re-routing to %d to cli_1 : [%d]: %s\n",ext_who, cli_recv_data, to_ext_DATA);
                fflush(stdout);
                int tmp2 = send(ext_who, to_ext_DATA,cli_recv_data,MSG_NOSIGNAL);
                if (tmp2 <= 0) printf("Cannot reply to client !!!!\n\n");
                cli_recv_data = -1;
                printf("%d bytes sent to soc %d.\n\n", tmp2, ext_who);
          }

     i_thread_1++; if(i_thread_1 > i_Maxi) i_thread_1=3; //verifie la bonne sante des thread (visible dans status)
   }//while(1)
   printf("Thread TCP_svr @%d exiting.\n", portno);
   //return 0;
}

//====================================================================
//====================================================================


void *connect_client( void *ptr )
{
   NB_Thread++; printf("...Thread %d/%d start (connect_client).\n", NB_Thread, NB_Thread_tot);

while(ithread1) {
    sleep(1);
    //printf("Req to Connect ?\n");

    if (ext_req == 1) {
      ext_req=0;  
      printf("---> Req to Connect 1\n");fflush(stdout);
    int portno, n;
    struct sockaddr_in serv_addr;
    struct hostent* server;

    char buffer[256];
    portno = ext_port;// ext

    cli_sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (cli_sockfd < 0) 
        error("ERROR opening socket");
    server = (struct hostent*) gethostbyname(ext_adr); //ext
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        cli_sockfd = -1;
       
    }else{
            bzero((char *) &serv_addr, sizeof(serv_addr));
            serv_addr.sin_family = AF_INET;
            bcopy((char *)server->h_addr, 
                 (char *)&serv_addr.sin_addr.s_addr,
                 server->h_length);
            serv_addr.sin_port = htons(portno);

            //________________Connect_______
            if (connect(cli_sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) 
                error("ERROR connecting");

            //___write___ff_fd_03
            buffer[0]='A';
            buffer[1]='B';
            buffer[2]='C';
            buffer[3]=0;

            client_is_connected = ext_who;//previens le systeme qu il est connecte
    }
 
    //-------------------------------------------------------------------   
    //=====OPTION: on peut repondre au terminal "connected" mais risque
    // de perturber le protocole TELNET
    //
    //
    //send(ext_who, "Connected." ,10,MSG_NOSIGNAL);
    //-------------------------------------------------------------------

    //n = write(cli_sockfd,buffer,strlen(buffer));

/* ____pas de lecture/ecriture ici____
    bzero(to_ext_DATA,256);
    n = read(cli_sockfd,to_ext_DATA,255);
    if (n < 0) 
         error("ERROR reading from socket");
    
    //ask_for_reply(1);
    send(ext_who, to_ext_DATA,strlen(to_ext_DATA),MSG_NOSIGNAL);  */
    //printf("%s\n",buffer);


   }//if req
   else{
     usleep(50000); //50 ms
   }
    i_thread_2++; if(i_thread_2 > i_Maxi) i_thread_2=3; //verifie la bonne sante des thread (visible dans status)
  }//while (1)
  printf("Thread CONNECT exiting.\n");
}

//====================================================================
//====================================================================

void *read_for_client( void *ptr )
{
  //printf("Thread read_for_client starting...\n");
  NB_Thread++; printf("...Thread %d/%d start (TCP read_for_client).\n", NB_Thread, NB_Thread_tot);

  int n,cpt,k=0;

  while(ithread1) {
    usleep(25000); //50 ms
    //printf("bcl read ?\n");

    if (client_is_connected > 1 ) {
       bzero(to_ext_DATA,MAXDATASIZE);
       printf("external read now...%d\n", cpt++);fflush(stdout);
       if (cpt > 100000) cpt=0;

       //n = read(cli_sockfd,to_ext_DATA,255);
       n = recv(cli_sockfd,to_ext_DATA,10240,0);
       if (n < 0) 
            error("ERROR reading from socket");
       if (n > 0 ) {
          cli_recv_data = n;
          printf("read_from_external : N= %d ; recv :%s\n",  n,  to_ext_DATA);
          for(k=0; k<n; k++)
            printf("x%02x ",  to_ext_DATA[k]);
          printf("\n");      
        }

        //gestion deconnection TBC !!!!
        if(n==0) client_is_connected=-1;
    } //if ext_who
 
    i_thread_3++; if(i_thread_3 > i_Maxi) i_thread_3=3; //verifie la bonne sante des thread (visible dans status)
  }//while
  printf("Thread read_for_client exiting.\n");
}

//====================================================================
void *RS232_read_bidon( void *ptr )
{
  NB_Thread++; printf("...Thread %d/%d BREAK (RS232_read_bidon).\n", NB_Thread, NB_Thread_tot);
   while (ithread1){
          usleep(2000000); //2000 ms
          //fprintf(stdout, "."); fflush(stdout);
          }
}

//====================================================================
void *RS232_read( void *ptr )
{
  //printf("Thread read_for_client starting...\n");
  NB_Thread++; printf("...Thread %d/%d start (RS232_read).\n", NB_Thread, NB_Thread_tot);

          int fd,c, res, n;
          struct termios oldtio,newtio;
          char mnemo[64], value[64];
          char to_soc[500]; //buffer to_socket listen_RS
          char indic='*';
        /* 
          Open modem device for reading and writing and not as controlling tty
          because we don't want to get killed if linenoise sends CTRL-C.
        */
         printf("  Thread %d try to open %s.\n", NB_Thread, SerialDevice);
         fd = open(SerialDevice, O_RDWR | O_NOCTTY );  //= devicename
         if (fd <0) {perror(SerialDevice); exit(-1); }
        
         tcgetattr(fd,&oldtio); /* save current serial port settings */
         bzero(&newtio, sizeof(newtio)); /* clear struct for new port settings */
        
        /* -----------------------------OLD
        BAUD  = B1200;   //1200 Baud
        DATABITS = CS7;
        STOPBITS = 0;
        PARITYON = PARENB; //odd
        PARITY = PARODD;   //odd
        --------------------------------/OLD
          BAUDRATE: Set bps rate. You could also use cfsetispeed and cfsetospeed.
          CRTSCTS : output hardware flow control (only used if the cable has
                    all necessary lines. See sect. 7 of Serial-HOWTO)
          CS8     : 8n1 (8bit,no parity,1 stopbit)
          CLOCAL  : local connection, no modem contol
          CREAD   : enable receiving characters
        */
         newtio.c_cflag = B1200    | CRTSCTS | CS7 | 0        | PARENB  | PARODD  | CLOCAL | CREAD;
       //newtio.c_cflag = BAUD     | CRTSCTS | CS7 | STOPBITS | PARITYON | PARITY | CLOCAL | CREAD;
      
       /*
          IGNPAR  : ignore bytes with parity errors
          ICRNL   : map CR to NL (otherwise a CR input on the other computer
                    will not terminate input)
          otherwise make device raw (no other input processing)
        */
         //newtio.c_iflag = IGNPAR | ICRNL;
       newtio.c_iflag = IGNPAR;
        /*
         Raw output.
        */
         newtio.c_oflag = 0; //newtio.c_oflag = 0;
         
        /*
          ICANON  : enable canonical input
          disable all echo functionality, and don't send signals to calling program
        */
         newtio.c_lflag = ICANON;// =2  //newtio.c_lflag = 0;       //ICANON;
         
        /* 
          initialize all control characters 
          default values can be found in /usr/include/termios.h, and are given
          in the comments, but we don't need them here
        */
         newtio.c_cc[VINTR]    = 0;     /* Ctrl-c */ 
         newtio.c_cc[VQUIT]    = 0;     /* Ctrl-\ */
         newtio.c_cc[VERASE]   = 0;     /* del */
         newtio.c_cc[VKILL]    = 0;     /* @ */
         newtio.c_cc[VEOF]     = 4;     /* Ctrl-d */
         newtio.c_cc[VTIME]    = 0;     /* inter-character timer unused */            //[VTIME]=0;
         newtio.c_cc[VMIN]     = 1;     /* blocking read until 1 character arrives */ //[VMIN]=1;
         newtio.c_cc[VSWTC]    = 0;     /* '\0' */
         newtio.c_cc[VSTART]   = 0;     /* Ctrl-q */ 
         newtio.c_cc[VSTOP]    = 0;     /* Ctrl-s */
         newtio.c_cc[VSUSP]    = 0;     /* Ctrl-z */
         newtio.c_cc[VEOL]     = 0;     /* '\0' */
         newtio.c_cc[VREPRINT] = 0;     /* Ctrl-r */
         newtio.c_cc[VDISCARD] = 0;     /* Ctrl-u */
         newtio.c_cc[VWERASE]  = 0;     /* Ctrl-w */
         newtio.c_cc[VLNEXT]   = 0;     /* Ctrl-v */
         newtio.c_cc[VEOL2]    = 0;     /* '\0' */
        
        /* 
          now clean the modem line and activate the settings for the port
        */
         tcflush(fd, TCIFLUSH);
         tcsetattr(fd,TCSANOW,&newtio);
        
        /*
          terminal settings done, now handle input
          In this example, inputting a 'z' at the beginning of a line will 
          exit the program.
        */
         //while (STOP==FALSE) {     /* loop until we have a terminating condition */
        //int MAX=50;
        //int jj;
        //for(jj=0; jj<MAX; jj++){
        while (ithread1){
          usleep(20000); //20 ms
         /* read blocks program execution until a line terminating character is 
            input, even if more than 255 chars are input. If the number
            of characters read is smaller than the number of chars available,
            subsequent reads will return the remaining chars. res will be set
            to the actual number of characters actually read */
            res = read(fd,bufRS,255); 
            if (res > 1 ) bufRS[res-2]=0;             /* set end of string, so we can printf */
            else {bufRS[0]='?';
                  bufRS[1]=0;
            }
            //printf("%d:%s.\n",res, bufRS);

         if( listen_RS > 1) { 
                if (RS_RAW == 1) {sprintf(to_soc, "%s\n",bufRS); fct_send_line(listen_RS,to_soc);}
         }


            if(res == -1) usleep(300000) ; //ralenti si rien lu !

                        //__rech_pattern__
                        sscanf(bufRS,"%s %s", mnemo, value);
                        //printf("----> MNEMO=%s(%d), VAL=%s\n", mnemo, mnemo,value);
                        if (strncmp (mnemo, "ADCO"    , 4) == 0) { ADCO    =atoi(value) ; }
                        if (strncmp (mnemo, "OPTARIF" , 7) == 0) { OPTARIF =atoi(value) ; }
                        if (strncmp (mnemo, "ISOUSC"  , 6) == 0) { ISOUSC  =atoi(value) ; }
                        if (strncmp (mnemo, "HCHC"    , 4) == 0) { HCHC    =atoi(value) ; }
                        if (strncmp (mnemo, "HCHP"    , 4) == 0) { HCHP    =atoi(value) ; }
                        if (strncmp (mnemo, "PTEC"    , 4) == 0) { sprintf(PTEC,"%s",value) ; }
                        if (strncmp (mnemo, "IINST1"  , 6) == 0) { IINST1  =atoi(value) ; }
                        if (strncmp (mnemo, "IINST2"  , 6) == 0) { IINST2  =atoi(value) ; }
                        if (strncmp (mnemo, "IINST3"  , 6) == 0) { IINST3  =atoi(value) ; }
                        if (strncmp (mnemo, "IMAX1"   , 5) == 0) { IMAX1   =atoi(value) ; }
                        if (strncmp (mnemo, "IMAX2"   , 5) == 0) { IMAX2   =atoi(value) ; }
                        if (strncmp (mnemo, "IMAX3"   , 5) == 0) { IMAX3   =atoi(value) ; }
                        if (strncmp (mnemo, "PMAX"    , 4) == 0) { PMAX    =atoi(value) ; }
                        if (strncmp (mnemo, "PAPP"    , 4) == 0) { PAPP    =atoi(value) ; }
                        if (strncmp (mnemo, "HHPHC"   , 5) == 0) { sprintf(HHPHC,"%s",value) ; }
                        if (strncmp (mnemo, "MOTDETAT", 8) == 0) { MOTDETAT=atoi(value) ; }
                        if (strncmp (mnemo, "PPOT"    , 4) == 0) { PPOT    =atoi(value) ; 
                                if( listen_RS > 1) { sprintf(to_soc, "HP= %d ;HC= %d ;i= %d  %d  %d\n",
                                                        HCHP, HCHC, IINST1, IINST2, IINST3); 
                                             fct_send_line(listen_RS,to_soc);}
                           if( soc_broad_232 > 1 ){ 
                                sprintf(to_soc, "broad: iii %d  %d  %d %c\n", IINST1, IINST2, IINST3, indic); 
                                n=send(soc_broad_232,to_soc,strlen(to_soc),MSG_NOSIGNAL);
                                if (indic == '.') indic='#'; else indic='.';
                                //usleep(750100); //750 ms
                                //printf("[DEBUG] send %d to RS broad\n",n);
                                if (n<0) connecte_broadcast();//reconnection si perte du lien !
                            }

                        } //if PPOT
           //printf("-----------------------> Simu     Th RS232 running ?\n");sleep(1);
           i_thread_4++; if(i_thread_4 > i_Maxi) i_thread_4=3; //verifie la bonne sante des thread (visible dans status)
         } //while thread
         /* restore the old port settings */
         tcsetattr(fd,TCSANOW,&oldtio);

  printf("Thread RS232_read exiting.\n");
}
//====================================================================
void *HEURE_auto( void *ptr )
{
  //printf("Thread read_for_client starting...\n");
  NB_Thread++; printf("...Thread %d/%d start (HEURE_auto).\n", NB_Thread, NB_Thread_tot);

  char ch1[256],ch2[256];
  char dj[10], dm[10], dd[10], dh[10], da[10];
  time_t mytime;

struct timeval tv;
struct timezone tz;
//struct tm *tm;
gettimeofday(&tv, &tz);
//tm=localtime(&tv.tv_sec);
//printf(" %d:%02d:%02d %d \n", tm->tm_hour, tm->tm_min,   tm->tm_sec, tv.tv_usec);
int us_start;

  int init_lcd=0;

  while (ithread1)
  {
     gettimeofday(&tv, &tz);us_start=tv.tv_usec;
     if(HEURE_enable){    

          if(init_lcd==0){    
            printf("Init LCD...\n");
            //init_LCD_hard( "Heure Init OK." ); // LPT only !!!
            init_lcd=1;
          }

        
        
        mytime = time(NULL);
        sprintf(ch1,ctime(&mytime)); //Thu Apr 14 17:41:56 2011
        sscanf(ch1,"%s %s %s %s %s", dj, dm, dd, dh, da);

        
        sprintf(ch2,"%s  %d %d %d   ",dh,  IINST1, IINST2, IINST3);

        send_1_line( 0, ch2 ); // Send 1 line to LCD4

          
        
        //printf("                                              +    \n");
    }//if enable
    //sleep(1); //tte les 1 s
    gettimeofday(&tv, &tz);delta_us=tv.tv_usec-us_start;
    usleep(915000); //tte les 0,8 s
    
    i_thread_5++; if(i_thread_5 > i_Maxi) i_thread_5=3; //verifie la bonne sante des thread (visible dans status)
  }
  
  printf("Thread HEURE_auto exiting.\n");
}

//====================================================================
void *UNO_read_non_blocking( void *ptr ) //ok version but blocking ???TBC
{
  //printf("Thread read_for_client starting...\n");
  char bufRS2[2556]; //read RS232
  int j;
  
  NB_Thread++; printf("...Thread %d/%d start (UNO_RS232_read blocking).\n", NB_Thread, NB_Thread_tot);

  int DB = 0 ; // DEBUG=1 , 0 any


          int c, res, n;
          struct termios oldtio,newtio;
          char mnemo[64], value[64];
          char to_soc[500]; //buffer to_socket listen_RS
          char indic='*';
        /* 
          Open modem device for reading and writing and not as controlling tty
          because we don't want to get killed if linenoise sends CTRL-C.
        */
         printf("  Thread %d try to open %s.\n", NB_Thread, UNOname);
         fd_uno = open(UNOname, O_RDWR | O_NOCTTY );  //= devicename
         if (fd_uno <0) {perror(UNOname); exit(-1); }
         
         if (DB==1) fprintf(stdout, " [UNO] open OK.  \n");
         tcgetattr(fd_uno,&oldtio); /* save current serial port settings */
         bzero(&newtio, sizeof(newtio)); /* clear struct for new port settings */
        
        /* -----------------------------OLD
        BAUD  = B1200;   //1200 Baud
        DATABITS = CS7;
        STOPBITS = 0;
        PARITYON = PARENB; //odd
        PARITY = PARODD;   //odd
        --------------------------------/OLD
          BAUDRATE: Set bps rate. You could also use cfsetispeed and cfsetospeed.
          CRTSCTS : output hardware flow control (only used if the cable has
                    all necessary lines. See sect. 7 of Serial-HOWTO)
          CS8     : 8n1 (8bit,no parity,1 stopbit)
          CLOCAL  : local connection, no modem contol
          CREAD   : enable receiving characters
        */
         newtio.c_cflag = B9600    | CRTSCTS | CS8 | 0        | 0  | CLOCAL | CREAD;
       //newtio.c_cflag = B9600    | CRTSCTS | CS8 | 0        | PARENB  | PARODD  | CLOCAL | CREAD;
       //newtio.c_cflag = BAUD     | CRTSCTS | CS7 | STOPBITS | PARITYON | PARITY | CLOCAL | CREAD;
      
       /*
          IGNPAR  : ignore bytes with parity errors
          ICRNL   : map CR to NL (otherwise a CR input on the other computer
                    will not terminate input)
          otherwise make device raw (no other input processing)
        */
         //newtio.c_iflag = IGNPAR | ICRNL;
       newtio.c_iflag = IGNPAR;
        /*
         Raw output.
        */
         newtio.c_oflag = 0; //newtio.c_oflag = 0;
         
        /*
          ICANON  : enable canonical input
          disable all echo functionality, and don't send signals to calling program
        */
         newtio.c_lflag = ICANON;// =2  //newtio.c_lflag = 0;       //ICANON;
         
        /* 
          initialize all control characters 
          default values can be found in /usr/include/termios.h, and are given
          in the comments, but we don't need them here
        */
         newtio.c_cc[VINTR]    = 0;     /* Ctrl-c */ 
         newtio.c_cc[VQUIT]    = 0;     /* Ctrl-\ */
         newtio.c_cc[VERASE]   = 0;     /* del */
         newtio.c_cc[VKILL]    = 0;     /* @ */
         newtio.c_cc[VEOF]     = 4;     /* Ctrl-d */
         newtio.c_cc[VTIME]    = 0;     /* inter-character timer unused */            //[VTIME]=0;
         newtio.c_cc[VMIN]     = 1;     /* blocking read until 1 character arrives */ //[VMIN]=1;
         newtio.c_cc[VSWTC]    = 0;     /* '\0' */
         newtio.c_cc[VSTART]   = 0;     /* Ctrl-q */ 
         newtio.c_cc[VSTOP]    = 0;     /* Ctrl-s */
         newtio.c_cc[VSUSP]    = 0;     /* Ctrl-z */
         newtio.c_cc[VEOL]     = 0;     /* '\0' */
         newtio.c_cc[VREPRINT] = 0;     /* Ctrl-r */
         newtio.c_cc[VDISCARD] = 0;     /* Ctrl-u */
         newtio.c_cc[VWERASE]  = 0;     /* Ctrl-w */
         newtio.c_cc[VLNEXT]   = 0;     /* Ctrl-v */
         newtio.c_cc[VEOL2]    = 0;     /* '\0' */
        
        /* 
          now clean the modem line and activate the settings for the port
        */
         tcflush(fd_uno, TCIFLUSH);
         tcsetattr(fd_uno,TCSANOW,&newtio);
         if (DB==1) fprintf(stdout, " [UNO] Set attr OK.  \n");
        
        /*
          terminal settings done, now handle input
          In this example, inputting a 'z' at the beginning of a line will 
          exit the program.
        */
         //while (STOP==FALSE) {     /* loop until we have a terminating condition */
        //int MAX=50;
        //int jj;
        //for(jj=0; jj<MAX; jj++){
        while (ithread1){
          usleep(5000); //20 ms
         /* read blocks program execution until a line terminating character is 
            input, even if more than 255 chars are input. If the number
            of characters read is smaller than the number of chars available,
            subsequent reads will return the remaining chars. res will be set
            to the actual number of characters actually read */
              if (DB==1) fprintf(stdout, " [UNO] AV read.  [Th=%d]\n",i_thread_6);
            
            res = read(fd_uno,bufRS2,2550); 
            
              if (DB==1) fprintf(stdout, "     .....[UNO] AP read.  %d\n",res);
            
            if (res > 1 ) {
                          UNO_connected=1; 
                          bufRS2[res]=0;             /* set end of string, so we can printf */
                          if (DB==1) fprintf(stdout, " [UNO] %d: %s\n", res, bufRS2);
 
              //if value return them on TCP socket:
              if( listen_UNO > 1) { 
                sprintf(to_soc, "%s (%d)\n",bufRS2, res); fct_send_line(listen_UNO,to_soc);
              }
              // Memo of last 2 lines
              sprintf(memo_UNO2, "%s",memo_UNO);
              sprintf(memo_UNO, "%s",bufRS2);
              
              // Memo of last Geo Buffer
              if (strncmp (bufRS2, "Geo:" , 4) == 0) { sprintf(memo_GEO, "%s",bufRS2); }
              // Memo of last Temperature Buffer
              if (strncmp (bufRS2, "Temp:" , 5) == 0) { sprintf(memo_TH, "%s",bufRS2); }
              
              
              for (j=0; j<res; j++) {
                 global_UNO[ptrW]=bufRS2[j];
                 ptrW++;
                 if (ptrW > 16000) ptrW=0;
              }
            
            
            }else {bufRS2[0]='?';
                  bufRS2[1]=0;
            }
            //printf("%d:%s.\n",res, bufRS2);



            if(res <= 0 ) {
                usleep(100000) ; //ralenti si rien lu !
                //fprintf(stdout, " [UNO] wait car Nothing... res=%d.\n", res);
            }

                        //__rech_pattern__
                        //sscanf(bufRS2,"%s %s", mnemo, value);
                        //printf("----> MNEMO=%s(%d), VAL=%s\n", mnemo, mnemo,value);
                        //if (strncmp (mnemo, "ADCO"    , 4) == 0) { ADCO    =atoi(value) ; }
                        //if (strncmp (mnemo, "PPOT"    , 4) == 0) { PPOT    =atoi(value) ; }
                        
                        
           //printf("-----------------------> Simu     Th RS232 running ?\n");sleep(1);
           i_thread_6++; if(i_thread_6 > i_Maxi) i_thread_6=6; //verifie la bonne sante des thread (visible dans status)
         } //while thread
         /* restore the old port settings */
         tcsetattr(fd_uno,TCSANOW,&oldtio);

  printf("Thread UNO RS232_read exiting.\n");
}

//====================================================================
void *UNO_read_non_blocking_qui_fctne( void *ptr )
{
  //printf("Thread read_for_client starting...\n");
  NB_Thread++; printf("...Thread %d/%d start (UNO_read_non_blocking NON blocking!!!).\n", NB_Thread, NB_Thread_tot);

   int DB = 0 ; // DEBUG=1 , 0 any
   
   char line[100]; //buffer 1 ligne
   char to_soc[500]; //buffer to_socket listen_RS
   int m=0;
   unsigned char C1;
   
        

   int fd_uno,  c, res, i, error,j=0;
   char In1, Key;
   struct termios oldtio, newtio;       //place for old and new port settings for serial port
   struct sigaction saio;               //definition of signal action
   char buf[2556];                       //buffer for where data is put
   
   if (DB==1) fprintf(stdout, "[stdout] Start UNO RS232...\n");
   if (DB==1) fprintf(stderr, "[stderr] UNO err ok.\n");

   error=0;

        /*==============================================
         |||                                          |||
         |||        C  O  N  F  I  G    UNO  RS232    |||
         |||                                          |||
         ================================================*/

        BAUD  = B9600;   //1200 Baud
        DATABITS = CS8;
        STOPBITS = 0;
        PARITYON = 0; //odd
        PARITY = 0;   //odd
        
      //open the device(com port) to be non-blocking (read will return immediately)
      //fprintf(stdout, " RS open ?\r\n");
      fd_uno = open("/UNO", O_RDWR | O_NOCTTY | O_NONBLOCK);

        char buff[1024];
        char mnemo[32], value[32];


      if (fd_uno < 0) // ERR sur RS232 !
      {
         fprintf(stdout, " RS232  Not opened.........\r\n");
         perror("/UNO");

         fprintf(stdout, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n\n");
         printf("__Dev__mode : sur fichier simule.   start:\n");
        
        FILE *fid;
        fid=fopen("./edf1.asc","r");
        if (fid == NULL)printf("Cannot open simu file edf1.asc !\n");
        else{
        int j,i;
        

        //res = read((int) fid,buff,4);

        i=0;
        for(j=0; j<100; j++){

               C1 = getc(fid); //usleep(10000);
                
                buff[i]=C1;
        

                printf("%c",  C1); fflush(stdout);
                //printf("%d:%c ", C1, C1); fflush(stdout);
                if (C1 == 13) {  // Ret Chariot
                        buff[i]=0; 
                        //printf("\n__ %s __\n", buff); fflush(stdout);
                        //__rech_pattern__
                        sscanf(buff,"%s %s", mnemo, value);
                        //printf("----> MNEMO=%s(%d), VAL=%s\n", mnemo, mnemo,value);
                        if (strncmp (mnemo, "ADCO"    , 4) == 0) { ADCO    =atoi(value) ; }
                        if (strncmp (mnemo, "PPOT"    , 4) == 0) { PPOT    =atoi(value) ; }
                        i=-1;
                } //if C1==13
                if (C1 == 10) { i=-1;} //Ret line
                i++; 
            } //for char read

         fclose(fid);
        printf("\n___________Result______\nPAPP=%d\n", PAPP);
        } // else simu file exist
        printf("\n__End__dev_fichier_simule__\n");

        
      } //if fd_uno<0

      if (DB==1) fprintf(stdout, " UNO RS232 open.\n");

      //install the serial handler before making the device asynchronous
      saio.sa_handler = signal_handler_IO;
      sigemptyset(&saio.sa_mask);   //saio.sa_mask = 0;
      saio.sa_flags = 0;
      saio.sa_restorer = NULL;
      sigaction(SIGIO,&saio,NULL);
      
      if (DB==1) fprintf(stdout, "  -serial handler\n");

      // allow the process to receive SIGIO
      fcntl(fd_uno, F_SETOWN, getpid());
      // Make the file descriptor asynchronous (the manual page says only
      // O_APPEND and O_NONBLOCK, will work with F_SETFL...)
      fcntl(fd_uno, F_SETFL, FASYNC);
      if (DB==1) fprintf(stdout, "  -serial NON_BLOCKING\n");

      tcgetattr(fd_uno,&oldtio); // save current port settings 
      // set new port settings for canonical input processing 
      newtio.c_cflag = BAUD | CRTSCTS | DATABITS | STOPBITS | PARITYON | PARITY | CLOCAL | CREAD;
      newtio.c_iflag = IGNPAR;
      newtio.c_oflag = 0;
      newtio.c_lflag = 0;       //ICANON;
      newtio.c_cc[VMIN]=1;
      newtio.c_cc[VTIME]=0;
      tcflush(fd_uno, TCIFLUSH);
      tcsetattr(fd_uno,TCSANOW,&newtio);
      if (DB==1) fprintf(stdout, "  -serial Avant bcle\n");

      // loop while waiting for input. normally we would do something useful here
//      while (STOP==FALSE)//##CC A modifier !!!
//      ######################################
i=0;
        int bidon;
        int h;
        //for (h=0; h<100 ;h++)
        while (ithread1)
      {
         usleep(20000);
         //fprintf(stdout, "h=%d\n",h); // ___animation___
         // after receiving SIGIO, wait_flag = FALSE, input is available and can be read

         //___Simu_Mode__Listen_RS_____:_Suppr_/**/__ci-dessous__
         /*if( listen_RS > 1) { sprintf(to_soc, "HP= %d ;HC= %d ;I1= %d ;I2= %d ;I3= %d\n",
                                               HCHP,   HCHC,   IINST1, IINST2, IINST3); 
                              fct_send_line(listen_RS,to_soc);}*/
         //___/Simu_Mode__Listen_RS_____

         if (wait_flag==FALSE)  //if input is available
         {
            if (DB==1) fprintf(stdout, "  -serial READ now.... \n"); fflush(stdout);
            res = read(fd_uno,buf,2550);
            if (DB==1) fprintf(stdout, "  -serial READ %d\n", res);
            //fprintf(stdout, "R."); // ___animation___
            //fflush(stdout);  // ___animation___
            if (res>0)
            {
                //i=0; //orig
               for (m=0; m<res; m++)  //for all chars in string
               {
                 C1 = buf[m];
                


                buff[i]=C1;
                //printf("%c",  C1); fflush(stdout);
                //printf("[%s]",  buff); fflush(stdout);
                //printf("%c %d ",  C1, res); fflush(stdout);
                //printf("%d:%c ", C1, C1); fflush(stdout);
                if (C1 == 13) {  // Ret Chariot
                        buff[i]=0; 
                        //printf("\n__ %s __\n", buff); fflush(stdout);
                        //__rech_pattern__
                        if (DB==1) fprintf(stdout, "  -serial A line: %s\n", buff);
                        sscanf(buff,"%s %s", mnemo, value);
                        //printf("----> MNEMO=%s(%d), VAL=%s\n", mnemo, mnemo,value);
                        if (strncmp (mnemo, "Geo"    , 3) == 0) { bidon=1 ; }
                        
                        if( listen_UNO > 1) { sprintf(to_soc," %s\n", buff ); 
                                             fct_send_line(listen_UNO,to_soc);
                                           }
                        i=-1;
                } //if C1==13
                if (C1 == 10) { i=-1;} //Ret line
                i++; 
          
              }//for m
 
            }  //end if res>0
            wait_flag = TRUE;      /* wait for new input */

         }  //end if wait flag == FALSE // data to read
         else{
           usleep(200000); //200 ms
         }

        i_thread_6++; if(i_thread_6 > i_Maxi) i_thread_6=6; //verifie la bonne sante des thread (visible dans status)

      }  //while ithread1_____bcle___continue____
      
      
      // restore old port settings
      //fprintf(stdout, "________END ?______________\r\n",data);
      tcsetattr(fd_uno,TCSANOW,&oldtio);
      close(fd_uno);        //close the com port

     //fprintf(stdout, "________END ACQ______________\r\n");

     fprintf(stdout, "\n\n__END__\r\n");

  printf("Thread UNO_read exiting.\n");
}

//====================================================================
//
// Fin CODE ici.
//
//
//     OLD ci-dessous  (RS_232 non bloquant)
//
//====================================================================
//====================================================================
//====================================================================
//====================================================================
//====================================================================
void *RS232_read_non_blocking_BLOC( void *ptr )
{
  //printf("Thread read_for_client starting...\n");
  NB_Thread++; printf("...Thread %d/%d start (RS232_read_non_blocking).\n", NB_Thread, NB_Thread_tot);

   char line[100]; //buffer 1 ligne
   char to_soc[500]; //buffer to_socket listen_RS
   int m=0;
   unsigned char C1;
        

   int fd,  c, res, i, error,j=0;
   char In1, Key;
   struct termios oldtio, newtio;       //place for old and new port settings for serial port
   struct sigaction saio;               //definition of signal action
   char buf[255];                       //buffer for where data is put
   
   fprintf(stdout, "[stdout] Start RS232...\n");
   fprintf(stderr, "[stderr] err ok.\n");

   error=0;

      printf("Device=%s, Baud=%li\r\n",SerialDevice, Baud_Rate); //output the received setup parameters
     

      printf("Data Bits=%i  Stop Bits=%i  Parity=%i  Format=%i  Nb_Li=%i\r\n",Data_Bits, Stop_Bits, Parity, Format, NB_LI);
      

        /*==============================================
         |||                                          |||
         |||        C  O  N  F  I  G     RS232        |||
         |||                                          |||
         ================================================*/

        BAUD  = B1200;   //1200 Baud
        DATABITS = CS7;
        STOPBITS = 0;
        PARITYON = PARENB; //odd
        PARITY = PARODD;   //odd
        
      //open the device(com port) to be non-blocking (read will return immediately)
      //fprintf(stdout, " RS open ?\r\n");
      fd = open(SerialDevice, O_RDWR | O_NOCTTY | O_NONBLOCK);

        char buff[1024];
        char mnemo[32], value[32];


      if (fd < 0) // ERR sur RS232 !
      {
         fprintf(stdout, " RS232  Not opened.........\r\n");
         
         perror(SerialDevice);

         fprintf(stdout, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n\n");
         printf("__Dev__mode : sur fichier simule.   start:\n");
        
        FILE *fid;
        fid=fopen("./edf1.asc","r");
        if (fid == NULL)printf("Cannot open simu file edf1.asc !\n");
        else{
        int j,i;
        

        //res = read((int) fid,buff,4);

        i=0;
        for(j=0; j<100; j++){

               C1 = getc(fid); //usleep(10000);
                
                buff[i]=C1;
        

                printf("%c",  C1); fflush(stdout);
                //printf("%d:%c ", C1, C1); fflush(stdout);
                if (C1 == 13) {  // Ret Chariot
                        buff[i]=0; 
                        //printf("\n__ %s __\n", buff); fflush(stdout);
                        //__rech_pattern__
                        sscanf(buff,"%s %s", mnemo, value);
                        //printf("----> MNEMO=%s(%d), VAL=%s\n", mnemo, mnemo,value);
                        if (strncmp (mnemo, "ADCO"    , 4) == 0) { ADCO    =atoi(value) ; }
                        if (strncmp (mnemo, "OPTARIF" , 7) == 0) { OPTARIF =atoi(value) ; }
                        if (strncmp (mnemo, "ISOUSC"  , 6) == 0) { ISOUSC  =atoi(value) ; }
                        if (strncmp (mnemo, "HCHC"    , 4) == 0) { HCHC    =atoi(value) ; }
                        if (strncmp (mnemo, "HCHP"    , 4) == 0) { HCHP    =atoi(value) ; }
                        if (strncmp (mnemo, "PTEC"    , 4) == 0) { sprintf(PTEC,"%s",value) ; }
                        if (strncmp (mnemo, "IINST1"  , 6) == 0) { IINST1  =atoi(value) ; }
                        if (strncmp (mnemo, "IINST2"  , 6) == 0) { IINST2  =atoi(value) ; }
                        if (strncmp (mnemo, "IINST3"  , 6) == 0) { IINST3  =atoi(value) ; }
                        if (strncmp (mnemo, "IMAX1"   , 5) == 0) { IMAX1   =atoi(value) ; }
                        if (strncmp (mnemo, "IMAX2"   , 5) == 0) { IMAX2   =atoi(value) ; }
                        if (strncmp (mnemo, "IMAX3"   , 5) == 0) { IMAX3   =atoi(value) ; }
                        if (strncmp (mnemo, "PMAX"    , 4) == 0) { PMAX    =atoi(value) ; }
                        if (strncmp (mnemo, "PAPP"    , 4) == 0) { PAPP    =atoi(value) ; }
                        if (strncmp (mnemo, "HHPHC"   , 5) == 0) { sprintf(HHPHC,"%s",value) ; }
                        if (strncmp (mnemo, "MOTDETAT", 8) == 0) { MOTDETAT=atoi(value) ; }
                        if (strncmp (mnemo, "PPOT"    , 4) == 0) { PPOT    =atoi(value) ; }
                        i=-1;
                } //if C1==13
                if (C1 == 10) { i=-1;} //Ret line
                i++; 
            } //for char read

         fclose(fid);
        printf("\n___________Result______\nPAPP=%d\n", PAPP);
        } // else simu file exist
        printf("HCHP=%d\n", HCHP);
        printf("HCHC=%d\n", HCHC);
        printf("\n__End__dev_fichier_simule__\n");

        
      } //if fd<0

      fprintf(stdout, " RS232 open.\n");

      //install the serial handler before making the device asynchronous
      saio.sa_handler = signal_handler_IO;
      sigemptyset(&saio.sa_mask);   //saio.sa_mask = 0;
      saio.sa_flags = 0;
      saio.sa_restorer = NULL;
      sigaction(SIGIO,&saio,NULL);

      // allow the process to receive SIGIO
      fcntl(fd, F_SETOWN, getpid());
      // Make the file descriptor asynchronous (the manual page says only
      // O_APPEND and O_NONBLOCK, will work with F_SETFL...)
      fcntl(fd, F_SETFL, FASYNC);

      tcgetattr(fd,&oldtio); // save current port settings 
      // set new port settings for canonical input processing 
      newtio.c_cflag = BAUD | CRTSCTS | DATABITS | STOPBITS | PARITYON | PARITY | CLOCAL | CREAD;
      newtio.c_iflag = IGNPAR;
      newtio.c_oflag = 0;
      newtio.c_lflag = 0;       //ICANON;
      newtio.c_cc[VMIN]=1;
      newtio.c_cc[VTIME]=0;
      tcflush(fd, TCIFLUSH);
      tcsetattr(fd,TCSANOW,&newtio);

      // loop while waiting for input. normally we would do something useful here
//      while (STOP==FALSE)//##CC A modifier !!!
//      ######################################
i=0;
        int h;
        //for (h=0; h<100 ;h++)
        while (ithread1)
      {
         usleep(20000);
         //fprintf(stdout, "h=%d\n",h); // ___animation___
         // after receiving SIGIO, wait_flag = FALSE, input is available and can be read

         //___Simu_Mode__Listen_RS_____:_Suppr_/**/__ci-dessous__
         /*if( listen_RS > 1) { sprintf(to_soc, "HP= %d ;HC= %d ;I1= %d ;I2= %d ;I3= %d\n",
                                               HCHP,   HCHC,   IINST1, IINST2, IINST3); 
                              fct_send_line(listen_RS,to_soc);}*/
         //___/Simu_Mode__Listen_RS_____

         if (wait_flag==FALSE)  //if input is available
         {
            res = read(fd,buf,255);
            //fprintf(stdout, "R."); // ___animation___
            //fflush(stdout);  // ___animation___
            if (res>0)
            {
                //i=0; //orig
               for (m=0; m<res; m++)  //for all chars in string
               {
                 C1 = buf[m];
                if( listen_RS > 1) { 
                        if (RS_RAW == 1) {sprintf(to_soc, "%c",C1); fct_send_line(listen_RS,to_soc);}
                }


                buff[i]=C1;
                //printf("%c",  C1); fflush(stdout);
                //printf("[%s]",  buff); fflush(stdout);
                //printf("%c %d ",  C1, res); fflush(stdout);
                //printf("%d:%c ", C1, C1); fflush(stdout);
                if (C1 == 13) {  // Ret Chariot
                        buff[i]=0; 
                        //printf("\n__ %s __\n", buff); fflush(stdout);
                        //__rech_pattern__
                        sscanf(buff,"%s %s", mnemo, value);
                        //printf("----> MNEMO=%s(%d), VAL=%s\n", mnemo, mnemo,value);
                        if (strncmp (mnemo, "ADCO"    , 4) == 0) { ADCO    =atoi(value) ; }
                        if (strncmp (mnemo, "OPTARIF" , 7) == 0) { OPTARIF =atoi(value) ; }
                        if (strncmp (mnemo, "ISOUSC"  , 6) == 0) { ISOUSC  =atoi(value) ; }
                        if (strncmp (mnemo, "HCHC"    , 4) == 0) { HCHC    =atoi(value) ; }
                        if (strncmp (mnemo, "HCHP"    , 4) == 0) { HCHP    =atoi(value) ; }
                        if (strncmp (mnemo, "PTEC"    , 4) == 0) { sprintf(PTEC,"%s",value) ; }
                        if (strncmp (mnemo, "IINST1"  , 6) == 0) { IINST1  =atoi(value) ; }
                        if (strncmp (mnemo, "IINST2"  , 6) == 0) { IINST2  =atoi(value) ; }
                        if (strncmp (mnemo, "IINST3"  , 6) == 0) { IINST3  =atoi(value) ; }
                        if (strncmp (mnemo, "IMAX1"   , 5) == 0) { IMAX1   =atoi(value) ; }
                        if (strncmp (mnemo, "IMAX2"   , 5) == 0) { IMAX2   =atoi(value) ; }
                        if (strncmp (mnemo, "IMAX3"   , 5) == 0) { IMAX3   =atoi(value) ; }
                        if (strncmp (mnemo, "PMAX"    , 4) == 0) { PMAX    =atoi(value) ; }
                        if (strncmp (mnemo, "PAPP"    , 4) == 0) { PAPP    =atoi(value) ; }
                        if (strncmp (mnemo, "HHPHC"   , 5) == 0) { sprintf(HHPHC,"%s",value) ; }
                        if (strncmp (mnemo, "MOTDETAT", 8) == 0) { MOTDETAT=atoi(value) ; }
                        if (strncmp (mnemo, "PPOT"    , 4) == 0) { PPOT    =atoi(value) ; 
                                if( listen_RS > 1) { sprintf(to_soc, "HP= %d ;HC= %d ;I1= %d ;I2= %d ;I3= %d\n",
                                                        HCHP, HCHC, IINST1, IINST2, IINST3); 
                                             fct_send_line(listen_RS,to_soc);}}
                        i=-1;
                } //if C1==13
                if (C1 == 10) { i=-1;} //Ret line
                i++; 

               
                }//for m
 
            }  //end if res>0
            wait_flag = TRUE;      /* wait for new input */

         }  //end if wait flag == FALSE


      }  //while stop==FALSE
      // restore old port settings
      //fprintf(stdout, "________END ?______________\r\n",data);
      tcsetattr(fd,TCSANOW,&oldtio);
      close(fd);        //close the com port

     //fprintf(stdout, "________END ACQ______________\r\n");

     fprintf(stdout, "\n\n__END__\r\n");

  printf("Thread RS232_read exiting.\n");
}


/***************************************************************************
* signal handler. sets wait_flag to FALSE, to indicate above loop that     *
* characters have been received.                                           *
***************************************************************************/

void signal_handler_IO (int status)
{
//    printf("received SIGIO signal.\n");
  // fprintf(stdout, "  >>>>>> received SIGIO signal   %d <<<<<<<<\n", status);
   wait_flag = FALSE;
}
